var QuartzNormal = function () {

    this.$grid_selector = $("#quartz_normal_grid_table");
    this.pager_selector = "#quartz_normal_grid_pager";

    this.URL = {
        EDIT: '/quartz/normal/reschedule',
        ADD: '/quartz/normal/add',
        ALL: '/quartz/normal/get/all',

        QUARTZ_PAUSE: '/quartz/normal/pause',
        QUARTZ_RESUME: '/quartz/normal/resume',
        QUARTZ_DELETE: '/quartz/normal/del'
    };

    var operatingTemplate = _.template('<div class="btn-group">' +
        '<button id="delete_job_{{rowId}}" class="btn btn-sm btn-danger delete-job">删除</button>' +
        '<button id="pause_job_{{rowId}}" class="btn btn-sm btn-warning pause-job">停用</button>' +
        '<button id="resume_job_{{rowId}}" class="btn btn-sm btn-primary resume-job">启用</button></div>');
    this.colModel = [
        {
            key: true, hidden: true, editable: true, formatter: function (cellValue, row) {
                return row.rowId;
            }
        },
        {name: 'jobName', fixed: true, width: 150},
        {name: 'jobClassName'},
        {name: 'statusName', fixed: true, width: 50},
        {name: 'description'},
        {name: 'cronExpression'},
        {
            formatter: function (cellValue, row) {
                return operatingTemplate({rowId: row.rowId});
            },
            fixed: true, width: 160
        }
    ];
    this.options = {
        url: this.URL.ALL,
        datatype: "json",
        pager: this.pager_selector,
        sortname: this.colModel[2].name,
        caption: "任务列表",
        colNames: ['流水号', '任务名称', '任务执行类', '状态', '备注', '表达式', '操作'],
        colModel: this.colModel,
        navbarDefaultIcon: {
            add: false,
            edit: false,
            view: false,
            del: false
        }
    };
    this.tempalte = _.template('\
    <div style="padding: 12px;">\
        <form method="post" class="form-horizontal">\
            <div class="form-group">\
                <label class="col-md-1 control-label">任务类名</label>\
                <div class="col-md-11">\
                    <input class="form-control" name="jobClassName" value="{{jobClassName}}">\
                </div>\
            </div>\
            <div class="form-group">\
                <label class="col-md-1 control-label">Cron</label>\
                <div class="col-md-5">\
                    <input class="form-control" value="{{cronExpression}}" name="cronExpression" placeholder="输入Cron表达式">\
                </div>\
                <label class="col-md-1 control-label">名称</label>\
                <div class="col-md-5">\
                    <input class="form-control" value="{{jobName}}" name="jobName" placeholder="不可重复">\
                </div>\
            </div>\
            <div class="form-group">\
                <label class="col-md-1 control-label">备注</label>\
                <div class="col-md-11">\
                    <input class="form-control" value="{{description}}" name="description">\
                </div>\
            </div>\
        </form>\
    </div>\
    ');
};

QuartzNormal.prototype = {
    // 初始化表格
    initGird: function () {
        var self = this;
        this.$grid_selector.xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "删除",
                buttonicon: "fa fa-trash-o red",
                onClickButton: function () {
                    $(this).getGridSelectedRow(function (rowData) {
                        self.deleteUI(rowData);
                    });
                },
                position: "first"
            })
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "编辑",
                buttonicon: "fa fa-pencil blue",
                onClickButton: function () {
                    $(this).getGridSelectedRow(function (rowData) {
                        self.editUI(rowData)
                    });
                },
                position: "first"
            })
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "添加",
                buttonicon: "fa fa-plus-circle purple",
                onClickButton: function () {
                    self.addUI()
                },
                position: "first"
            });
        // 绑定删除事件
        this.$grid_selector.delegate('.delete-job', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[2];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.deleteUI(row);
        });
        // 绑定暂停事件
        this.$grid_selector.delegate('.pause-job', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[2];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            $.xumf.ajaxAndLoading({
                url: self.URL.QUARTZ_PAUSE,
                data: {jobName: row.jobName}
            }).done(function (res) {
                $.xumf.gritter(res);
                res.success && self.$grid_selector.trigger('reloadGrid');
            });
        });
        // 绑定启用事件
        this.$grid_selector.delegate('.resume-job', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[2];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);

            $.xumf.ajaxAndLoading({
                url: self.URL.QUARTZ_RESUME,
                data: {jobName: row.jobName}
            }).done(function (res) {
                $.xumf.gritter(res);
                res.success && self.$grid_selector.trigger('reloadGrid');
            });
        })
    },
    /**
     * 增添定时器
     */
    addUI: function () {

        this.modifyUI('新增', this.URL.ADD);
    },
    /**
     * 删除
     * @param rowData 行的数据
     */
    deleteUI: function (rowData) {
        var self = this;
        $.xumf.confirm('是否删除定时任务', function (index) {
            $.xumf.ajaxAndLoading({
                url: self.URL.QUARTZ_DELETE,
                data: {jobName: rowData.jobName}
            }).done(function (res) {
                $.xumf.gritter(res);
                if (res.success) {
                    layer.close(index);
                    res.success && self.$grid_selector.trigger('reloadGrid');
                }
            });
        });
    },
    /**
     * 编辑
     * @param rowData 行的数据
     */
    editUI: function (rowData) {
        this.modifyUI('编辑', this.URL.EDIT, rowData);
    },
    modifyUI: function (title, url, data) {

        var defaultValues = $.extend({
            jobName: '',
            cronExpression: '',
            description: '',
            jobClassName: ''
        }, data);
        var self = this;
        var success = function (layero, index) {
            var $form = $(layero).find('form');

            if (data) {
                $form.find('input[name=jobName]').attr("readonly", true);
                $form.find('input[name=jobClassName]').attr("readonly", true);
            }
        };

        layer.open({
            title: title,
            area: ["650px", "300px"],
            content: this.tempalte(defaultValues),
            success: success,
            yes: function (index, layero) {

                var $form = $(layero).find('form');
                $form.validate({
                    rules: {
                        jobName: {required: true},
                        jobClassName: {required: true},
                        cronExpression: {required: true},
                        description: {required: true}
                    }
                });
                // 验证成功
                $form.valid() && $form.attr('action', url).ajaxSubmit({
                    success: function (res) {
                        layer.close(index);
                        $.xumf.gritter(res);
                        res.success && self.$grid_selector.trigger('reloadGrid')
                    }
                })
            }
        });
    }
};